package com.gexiaobao.pigeon.ui.pilot.activity

import android.annotation.SuppressLint
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.maps.AMap
import com.amap.api.maps.AMapUtils
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.Marker
import com.amap.api.maps.model.MarkerOptions
import com.amap.api.maps.model.Polyline
import com.amap.api.maps.model.PolylineOptions
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.ext.initClose
import com.gexiaobao.pigeon.app.util.AMapUtil
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.databinding.ActivityMapDistanceBinding
import com.gexiaobao.pigeon.viewmodel.ReleaseMissionViewModel
import me.hgj.jetpackmvvm.util.LogUtils
import java.math.RoundingMode
import java.text.DecimalFormat
import java.text.SimpleDateFormat
import java.util.Date

/**
 * @Author      : hxw
 * @Date        : 2023/6/1 11:34
 * @Describe    : 距离测算
 */
class MapDistanceActivity : BaseActivity<ReleaseMissionViewModel, ActivityMapDistanceBinding>() {

    private var id: String = ""
    var addPolyline: Polyline? = null
    var latitude: Double = 0.00
    var longitude: Double = 0.00

    //声明mLocationClient对象
    lateinit var mLocationClient: AMapLocationClient

    //声明mLocationOption对象
    lateinit var mLocationOption: AMapLocationClientOption

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.mineToolsMapDis.onCreate(savedInstanceState)
        mDatabind.includeBar.toolbar.initClose("距离测算") {
            finish()
        }
        id = intent.getStringExtra("id").toString()
        initData()
    }

    @SuppressLint("SimpleDateFormat")
    fun initData() {
        //设置是否只定位一次,默认为false
        mLocationClient = AMapLocationClient(this)
        //初始化定位参数
        mLocationOption = AMapLocationClientOption()
        //设置定位监听
        mLocationClient.setLocationListener {
            if (it != null) {
                if (it.errorCode === 0) {
                    //定位成功回调信息，设置相关消息
                    it.locationType //获取当前定位结果来源，如网络定位结果，详见定位类型表
                    it.latitude //获取纬度
                    it.longitude //获取经度
                    it.accuracy //获取精度信息

                    initLatLngDis(it.latitude, it.longitude, latitude, longitude)

                    val df = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                    val date = Date(it.time)
                    df.format(date) //定位时间
                } else {
                    AMapUtil.buildMsgSingle(this, "请检查定位权限", "好", {})
                    //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                    LogUtils.debugInfo("AmapError", ("location Error, ErrCode:" + it.errorCode) + ", errInfo:" + it.errorInfo)
                }
            }
        }
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.interval = 2000
        //设置定位参数
        mLocationOption.isOnceLocation = true
        mLocationClient.setLocationOption(mLocationOption)
        mViewModel.getLocation(id)
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.homingLResult.observe(this) {
            if (it == null) {
                RxToast.showToast("获取组织定位错误")
                return@observe
            }
            if (TextUtils.isEmpty(it.orgLat) && TextUtils.isEmpty(it.orgLong)) {
                RxToast.showToast("获取组织定位错误")
                return@observe
            }
            latitude = it.orgLat.toDouble()
            longitude = it.orgLong.toDouble()
            //启动定位
            mLocationClient.startLocation()
        }
    }

    @SuppressLint("SetTextI18n")
    private fun initLatLngDis(startLat: Double, startLon: Double, endLat: Double, endLong: Double) {
        val df = DecimalFormat("0.00")
        df.roundingMode = RoundingMode.HALF_UP

        val latLngStartLocal = LatLng(startLat, startLon)
        val latLngOrg = LatLng(endLat, endLong)
        mDatabind.toolsMapPullToDis.text = getString(R.string.mine_tools_map_distance_activity_two_point_distance) + df.format(
            AMapUtils.calculateLineDistance(
                latLngStartLocal,
                latLngOrg
            ) / 1000
        ) + getString(R.string.mine_tools_map_distance_activity_start_point_meter)
        mDatabind.mineToolsMapDis.map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLngStartLocal, 48.0f))


        val markerOption1 = MarkerOptions()
        markerOption1.position(latLngStartLocal)
        markerOption1.title(getString(R.string.mine_tools_map_distance_activity_start_point))
        markerOption1.draggable(true)

        markerOption1.icon(
            BitmapDescriptorFactory.fromBitmap(
                BitmapFactory
                    .decodeResource(resources, R.mipmap.bisai_my_)
            )
        )

        val markerOption2 = MarkerOptions()
        markerOption2.position(latLngOrg)
        markerOption2.title(getString(R.string.mine_tools_map_distance_activity_end_point))
        markerOption2.draggable(false)
        markerOption2.icon(
            BitmapDescriptorFactory.fromBitmap(
                BitmapFactory
                    .decodeResource(resources, R.mipmap.bisai_wodexiaoxi_my_)
            )
        )

        mDatabind.mineToolsMapDis.map.addMarker(markerOption1)
        mDatabind.mineToolsMapDis.map.addMarker(markerOption2)


        val latLngList = ArrayList<LatLng>()
        latLngList.add(latLngStartLocal)
        latLngList.add(latLngOrg)
        val polylineOptions = PolylineOptions()
            .addAll(latLngList)
            .width(15.0f)
            .color(Color.argb(255, 233, 1, 1))
            .setDottedLine(true)
        addPolyline = mDatabind.mineToolsMapDis.map.addPolyline(polylineOptions)

        mDatabind.mineToolsMapDis.map.setOnMarkerDragListener(object : AMap.OnMarkerDragListener {
            @SuppressLint("SetTextI18n")
            override fun onMarkerDragEnd(p0: Marker) {
                val latLng = p0.position
                if (getString(R.string.mine_tools_map_distance_activity_start_point) == p0.title) {
                    polylineOptions.points[0] = latLng
                } else {
                    polylineOptions.points[1] = latLng
                }
                if (addPolyline != null) {
                    addPolyline!!.remove()
                    addPolyline = null
                }
                addPolyline = mDatabind.mineToolsMapDis.map.addPolyline(polylineOptions)

                mDatabind.toolsMapPullToDis.text = getString(R.string.mine_tools_map_distance_activity_two_point_distance) + df.format(
                    AMapUtils.calculateLineDistance(
                        polylineOptions.points[0],
                        polylineOptions.points[1]
                    ) / 1000
                ) + getString(R.string.mine_tools_map_distance_activity_start_point_meter)
            }

            override fun onMarkerDragStart(p0: Marker) {
                RxToast.showToast(R.string.mine_tools_map_distance_activity_drag_to_point)
            }

            override fun onMarkerDrag(p0: Marker) {}
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        mDatabind.mineToolsMapDis.onDestroy()
    }

    override fun onResume() {
        super.onResume()
        mDatabind.mineToolsMapDis.onResume()
    }

    override fun onPause() {
        super.onPause()
        mDatabind.mineToolsMapDis.onPause()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        mDatabind.mineToolsMapDis.onSaveInstanceState(outState)
    }
}